from rest_framework import serializers


class BookSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=16, min_length=2, error_messages={'min_length': '书名最少2位'}, source='title')
    price = serializers.CharField()
    pub_datetime = serializers.DateTimeField(source='pub_date')
    # source='' 里面可以是属性也可以是方法
    publish = serializers.CharField(source='publish.name')  # 相当于book.publish 所以会返回 __str__()方法的值
    authors = serializers.SerializerMethodField()  # 想获取所有作者信息，需要有一个以get开头的方法  get_字段名

    def get_authors(self, instance):
        # instance 就是book对象
        authors = instance.author.all()
        l1 = [{'name': author.name, 'age': author.age} for author in authors]
        return l1